<template>
   
        <div class="content">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item >
            <el-input v-model="lodingForm.form.name" placeholder="请输入账号、姓名、电话" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="lodingForm.form.status" clearable placeholder="用户状态" style="width:120px">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSerch" circle ><el-icon><Search /></el-icon></el-button>
          
            <el-button type="success" @click="onLoding"  >刷新</el-button>
         
            <el-button  @click="handleClickAdd" type="primary" plain ><el-icon><Plus /></el-icon>添加</el-button >
          </el-form-item>
        </el-form>
        <el-table row-key="id" empty-text="暂无数据" v-loading="lodingForm.loading"  @sort-change="sortChange" :data="tableData" default-expand-all style="width: 100%;height: calc(100vh - 182px);" border>
          <el-table-column fixed type="index" label="序号" min-width="55"></el-table-column>
          <el-table-column prop="name" label="名称" min-width="120" show-overflow-tooltip   />
          <el-table-column prop="content" label="备注" min-width="120" show-overflow-tooltip  align="center" />
          <el-table-column label="状态" min-width="120" prop="status"  sortable="custom"  align="center">
          <template #default="scope">
            <el-switch v-model="scope.row.status" @change="onStatus(scope.row.id)" >
              <template #active-action>
                <span class="custom-active-action">启</span>
              </template>
              <template #inactive-action>
                <span class="custom-inactive-action">禁</span>
              </template>
            </el-switch>
          </template>
          
        </el-table-column>
        <el-table-column label="添加时间" min-width="190" prop="created_at"  sortable="created_at"  align="center"></el-table-column>
          <el-table-column fixed="right" label="操作" min-width="140">
            <template #default="scope">
              <el-button type="primary" link class="button-edit" 
              size="small" @click="handleClickInfo(scope.row.id)">
              查看
            </el-button>
            <el-button type="success" link class="button-edit" 
              size="small" @click="handleClickEdit(scope.row.id)">
              修改
            </el-button>
              <el-popconfirm
                width="220"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="确认删除该数据?"
                @confirm="onConfirm(scope.row.id)"
              >
                <template #reference>
                  <el-button size="small"  type="danger" link >删除</el-button>
                </template>
  
                <template #actions="{ confirm, cancel }">
                  <el-button size="small" @click="cancel">否</el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="confirm"
                  >
                    是
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
  
        <el-pagination class="pagination" v-model:current-page="lodingForm.form.page" v-model:page-size="lodingForm.form.limit"
          :page-sizes="[10,50,100, 200, 300, 400]" :background="true" :size="size" 
          layout="total,  prev, pager, next, jumper" :total="lodingForm.data.total" 
          />
        </div>
  
    <el-dialog v-model="formDialog.show" :title="formDialog.title"  width="80%" align-center draggable>
      <formView  v-if="formDialog.show" :type="formDialog.type" :id="formDialog.id" @close-dialog="closeDialog"/>
    </el-dialog>
  
  
  </template>
  <script lang="ts" setup>
  import { ref, reactive, getCurrentInstance, onMounted } from 'vue'
  import { useRoute } from 'vue-router';
  import { roleApi } from '@/utils/api/role';
  import formView from './create.vue'
  import { ElMessage } from 'element-plus'
  const route = useRoute();
  console.log(route,'000'); // 输出当前路由的路径
  const { proxy } = getCurrentInstance(); // 获取当前Vue实例的代理对象，用于访问全局属性。
  interface Tree {
    label: string
    children?: Tree[]
  }
  
  
  const onLoding = () => {
    lodingForm.form.page = 1
    lodingForm.form.limit = 10
    lodingForm.form.name = ''
    lodingForm.form.status = null
    lodingForm.form.sortBy = {}
    getList()
  }
  const onSerch = () => {
    lodingForm.form.page = 1
    getList()
  
  }
  
  
  const size = ref<ComponentSize>('default')
  
  const sortChange = ({ column, prop, order }) => {
    lodingForm.form.sortBy = {};
    // 处理排序逻辑
    if (order === 'ascending') {
      order = 'asc'
      // getList();
    } else if (order === 'descending') {
      order = 'desc'
    } else {
      // 重置排序或进行其他操作
    }
    Object.assign(lodingForm.form.sortBy, {[prop]:order});
    getList();
        
  }
  const convertToTree = (data: any[]): Tree[] => {
    const tree = [];
    const map = {};
  
    // 第一步：创建一个以 id 为键的映射表
    data.forEach(item => {
      map[item.id] = { ...item, children: [] };
    });
  
    // 第二步：找出所有可能的父节点 id
    const allParentIds = new Set(data.map(item => item.pid));
  
    // 第三步：构建树形结构
    data.forEach(item => {
      if (!map[item.pid]) {
        // 如果该元素的 pid 不在 map 中，说明它没有父级，是根节点
        tree.push(map[item.id]);
      } else {
        // 否则，找到其父节点并将其添加到父节点的 children 数组中
        const parent = map[item.pid];
        if (parent) {
          parent.children.push(map[item.id]);
        }
      }
    });
  
    return tree;
  }
  
  const lodingForm = reactive({
   form:{
    name: '',
    status: null,
    page: 1,
    limit: 10,
    sortBy:{}
   },
   loading:false,
   data:{
    data:[],
    last_page: 0,
    limit: 0,
    page: 0,
    total: 0,
   }
  })
  const tableData = ref([])
  const getList = async () => {
    lodingForm.loading = true
    // tableData.value  = []
    const res = await roleApi.getlist(lodingForm.form)
    if(res.code === 200){
      lodingForm.data = res.data
      tableData.value = res.data.data
      tableData.value.forEach((item:any) => {
        item.status = item.status === 1 ? true : false
      })
    }else{
      tableData.value  = []
      ElMessage({
        type: res.type,
        message: res.message,
      })
    }
    lodingForm.loading = false 
  
  }
  
  const formDialog = reactive({
    show: false,
    id: null,
    type: 'add', 
  })
  const handleClickAdd = () => {
    formDialog.show = true
    formDialog.id = null
    formDialog.type = 'add'
    formDialog.title = '添加'
    console.log(2)
    // router.push({ name: 'companyCreate', params: { id: 0 } })
  }
  const closeDialog = () => {
    formDialog.show = false
    getList()
  }
  const handleClickInfo = (id: number) => {
    // router.push({ name: 'companyInfo', params: { id: id } })
    formDialog.show = true
    formDialog.title = '详情'
    formDialog.id = id
    formDialog.type = 'info'
  }
  
  const handleClickEdit = (id: number) => {
    formDialog.show = true
    formDialog.title = '修改'
    formDialog.id = id
    formDialog.type = 'edit'
    // router.push({ name: 'companyCreate', params: { id: id } })
  }
  //删除数据
  const onConfirm = async (id: number) => {
    lodingForm.loading = true
    await roleApi.delete({id:id})
    getList() 
  }
  //状态修改
  const onStatus = async (id: number) => {
    lodingForm.loading = true
    await roleApi.status({id:id})
    getList() 
  }
  
  onMounted(  async() => {
   getList()
  })
  
  
  </script>
  
  <style scoped>
  .demo-form-inline {
    padding-bottom: 0;
  }
  
  
  .rigthUser {
    width: 100%;
  }
  
  </style>